# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Announcement(models.Model):
    """公告模型 - 支持部门层级权限的公告系统"""
    _name = 'device.announcement'
    _description = '公告管理'
    _order = 'create_time desc, id desc'
    _rec_name = 'title'
    _inherit = ['device.permission.mixin']
    
    # 基础信息
    title = fields.Char('公告标题', required=True)
    content = fields.Text('公告内容', required=True)
    
    # 发布信息
    publisher_id = fields.Many2one('device.user', '发布人', required=True, default=lambda self: self._get_current_user())
    publisher_name = fields.Char('发布人姓名', related='publisher_id.nick_name', store=True)
    
    # 部门关联
    department_id = fields.Many2one('device.department', '发布部门', required=True, default=lambda self: self._get_current_user_department())
    department_name = fields.Char('发布部门名称', related='department_id.complete_name', store=True)
    
    # 公告状态
    status = fields.Selection([
        ('draft', '草稿'),
        ('published', '已发布'),
        ('withdrawn', '已撤回')
    ], string='公告状态', default='draft', required=True)
    
    # 公告类型
    announcement_type = fields.Selection([
        ('normal', '普通公告'),
        ('urgent', '紧急公告'),
        ('system', '系统公告')
    ], string='公告类型', default='normal', required=True)
    
    # 时间信息
    publish_date = fields.Datetime('发布时间')
    effective_date = fields.Datetime('生效时间', default=fields.Datetime.now)
    expire_date = fields.Datetime('过期时间')
    
    # 可见性控制
    visibility_scope = fields.Selection([
        ('department', '本部门'),
        ('department_and_child', '本部门及下属部门'),
        ('all', '全公司')
    ], string='可见范围', default='department', required=True)
    
    # 置顶和重要标记
    is_top = fields.Boolean('是否置顶', default=False)
    is_important = fields.Boolean('是否重要', default=False)
    
    # 阅读统计
    read_count = fields.Integer('阅读次数', default=0)
    read_user_ids = fields.Many2many(
        'device.user',
        'device_announcement_read_rel',
        'announcement_id',
        'user_id',
        string='已读用户'
    )
    read_user_count = fields.Integer('已读人数', compute='_compute_read_user_count', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('read_user_ids')
    def _compute_read_user_count(self):
        for announcement in self:
            announcement.read_user_count = len(announcement.read_user_ids)
    
    def _get_current_user(self):
        """获取当前用户"""
        # 这里需要根据实际的用户认证逻辑来获取当前用户
        return self.env['device.user'].search([], limit=1)
    
    def _get_current_user_department(self):
        """获取当前用户部门"""
        current_user = self._get_current_user()
        return current_user.department_id if current_user else False
    
    @api.constrains('effective_date', 'expire_date')
    def _check_dates(self):
        for record in self:
            if record.expire_date and record.effective_date:
                if record.expire_date < record.effective_date:
                    raise ValidationError('过期时间不能早于生效时间。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_publish(self):
        """发布公告"""
        self.write({
            'status': 'published',
            'publish_date': fields.Datetime.now()
        })
    
    def action_withdraw(self):
        """撤回公告"""
        self.write({'status': 'withdrawn'})
    
    def action_mark_as_read(self, user_id=None):
        """标记为已读"""
        if not user_id:
            user_id = self._get_current_user().id
        
        if user_id and user_id not in self.read_user_ids.ids:
            self.write({
                'read_user_ids': [(4, user_id)],
                'read_count': self.read_count + 1
            })
    
    def get_visible_announcements(self, user_id=None):
        """获取用户可见的公告列表"""
        if not user_id:
            current_user = self._get_current_user()
            if not current_user:
                return self.env['device.announcement']
            user_id = current_user.id
        else:
            current_user = self.env['device.user'].browse(user_id)
        
        # 超级管理员可以看到所有公告
        if current_user.is_admin:
            return self.search([('status', '=', 'published')])
        
        user_dept = current_user.department_id
        if not user_dept:
            return self.env['device.announcement']
        
        # 构建可见公告的域条件
        domain = [('status', '=', 'published')]
        
        # 添加时间过滤条件
        now = fields.Datetime.now()
        domain.extend([
            ('effective_date', '<=', now),
            '|',
            ('expire_date', '=', False),
            ('expire_date', '>', now)
        ])
        
        # 构建部门可见性条件
        dept_conditions = []
        
        # 1. 全公司可见的公告
        dept_conditions.append(('visibility_scope', '=', 'all'))
        
        # 2. 本部门发布的公告
        dept_conditions.append([
            ('department_id', '=', user_dept.id),
            ('visibility_scope', 'in', ['department', 'department_and_child'])
        ])
        
        # 3. 上级部门发布且范围包含下属部门的公告
        parent_depts = user_dept.get_parent_departments()
        if parent_depts:
            dept_conditions.append([
                ('department_id', 'in', parent_depts.ids),
                ('visibility_scope', '=', 'department_and_child')
            ])
        
        # 组合部门条件
        if len(dept_conditions) > 1:
            domain.append('|' * (len(dept_conditions) - 1))
        domain.extend(dept_conditions)
        
        return self.search(domain, order='is_top desc, is_important desc, create_time desc')
    
    def get_unread_count(self, user_id=None):
        """获取用户未读公告数量"""
        if not user_id:
            current_user = self._get_current_user()
            if not current_user:
                return 0
            user_id = current_user.id
        
        visible_announcements = self.get_visible_announcements(user_id)
        unread_announcements = visible_announcements.filtered(
            lambda a: user_id not in a.read_user_ids.ids
        )
        return len(unread_announcements)
    
    def check_publish_permission(self, user_id=None):
        """检查发布权限"""
        if not user_id:
            current_user = self._get_current_user()
            if not current_user:
                return False
            user_id = current_user.id
        else:
            current_user = self.env['device.user'].browse(user_id)
        
        # 超级管理员可以发布
        if current_user.is_admin:
            return True
        
        # 检查是否是部门负责人
        user_dept = current_user.department_id
        if user_dept and user_dept.device_leader_id.id == user_id:
            return True
        
        # 检查是否有公告发布权限
        return current_user.check_user_permissions('announcement:publish')

